package dao.Impl;

import dao.BaseDao;
import dao.CardDao;
import entity.Card;

import javax.swing.plaf.SliderUI;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CardDaoImpl extends BaseDao implements CardDao {
    Card card = null;
    @Override
    public List<Card> info() {
        conn =  super.getConnection();
        List<Card> list = new ArrayList<>();
        try{
            String sql = "select * from card order by createDate desc ";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()){
                card = new Card();
                card.setId(rs.getInt("id"));
                card.setUserName(rs.getString("userName"));
                card.setIdNumber(rs.getString("idNumber"));
                card.setCreateDate(rs.getString("createDate"));
                card.setStatus(rs.getInt("status"));
                list.add(card);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(conn,pstmt,rs);
        }
        return list;
    }

    @Override
    public int inset(Card card) {
        conn = super.getConnection();
        int i  =0;
        try{
            String sql = "INSERT INTO `microblog`.`card`( `userName`, `idNumber`, `status`, `createDate`) VALUES (?,?,?,?);";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,card.getUserName());
            pstmt.setString(2,card.getIdNumber());
            pstmt.setInt(3,card.getStatus());
            pstmt.setString(4,card.getCreateDate());
            i = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(conn,pstmt,rs);
        }
        return i;
    }

    @Override
    public int update(int id, int status) {
        int i  = 0;
        int s=0;
        if (status==1){
            s=0;
        }else{
            s=1;
        }
        conn = super.getConnection();
        try {
            String sql = "UPDATE `microblog`.`card` SET `status`= ?  WHERE `id` = ?;";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1,s);
            pstmt.setInt(2,id);
            i=pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(conn,pstmt,rs);
        }
        return i;
    }

    @Override
    public boolean addIdNumber(String idNumber) {
        conn = super.getConnection();
        boolean fs = false;
        try {
            pstmt = conn.prepareStatement("select * from card where idNumber = ? ");
            pstmt.setString(1,idNumber);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                fs = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            closeAll(conn,pstmt,rs);
        }
        return fs;
    }

}
